package com.tyf.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.tyf.util.Result;

/**
 * Servlet implementation class ImgServlet
 */
@WebServlet("/ImgServlet")
public class ImgServlet extends BaseServlet {
	/**
	 * localhost:8080/upload-demo/ImgServlet?method=uploadImg
	 * 
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	public void uploadImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 输出对象
		PrintWriter out = resp.getWriter();
		// 1.创建SmartUpload一个上传对象
		SmartUpload smart = new SmartUpload();
		// 2.设置字符集
		smart.setCharset("utf-8");
		// 3.初始化
		smart.initialize(getServletConfig(), req, resp);
		try {
			// 4.上传文件
			smart.upload();
			// 5.保存文件到指定位置(save只提供路径，使用原文件名上传文件)
			smart.save("/imgs");
			// 获取文件名
			String filename = smart.getFiles().getFile(0).getFileName();
			// 成功：将数据返回
			out.print(Result.toClient(0, "新图片上传成功", filename));
		} catch (SmartUploadException e) {
			e.printStackTrace();
			// 失败：将数据返回
			out.print(Result.toClient(1, "图片上传失败"));
		}
		out.flush();
		out.close();
	}

}
